package log

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"log"
	"os"
	ld "pear-admin-layui-go/app/sys/log/domain"
	"pear-admin-layui-go/framework/login_filter"
	"time"
)

type CustomResponseWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w CustomResponseWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

func (w CustomResponseWriter) WriteString(s string) (int, error) {
	w.body.WriteString(s)
	return w.ResponseWriter.WriteString(s)
}

func WebLog() gin.HandlerFunc {

	src, err := os.OpenFile("web.log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModeAppend)
	if err != nil {
		log.Println(err)
	}

	logger := logrus.New()
	logger.Out = src
	logger.SetLevel(logrus.DebugLevel)
	logger.SetFormatter(&logrus.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	return func(c *gin.Context) {
		start := time.Now().Unix()
		c.Next()
		end := time.Now().Unix()
		cCp := c.Copy()

		go func() {

			blw := &CustomResponseWriter{body: bytes.NewBufferString(""), ResponseWriter: cCp.Writer}
			cCp.Writer = blw

			req := cCp.Request
			url := req.URL
			user, _ := login_filter.GetCurrentUser(cCp)

			var param string
			var result string
			if req.Method == "POST" {
				marshal, _ := json.Marshal(cCp.Request.PostForm)
				param = string(marshal)
				result = blw.body.String()
			}

			logDb := ld.LogDb{
				StartTime:  start,
				EndTime:    end,
				SpendTime:  end - start,
				Status:     cCp.Writer.Status(),
				Result:     result,
				Host:       url.Host,
				Ipaddr:     cCp.ClientIP(),
				Url:        url.Path,
				Method:     req.Method,
				Param:      param,
				UserAgent:  cCp.GetHeader("User-Agent"),
				CreateBy:   user.Id,
				CreateName: user.Username,
				CreateTime: time.Now().Unix(),
			}

			//logger.Infof("StartTime = %v, EndTime = %v, SpendTime = %v, Host = %v, Url = %v, Ipaddr = %v, "+
			//	"Method = %v, Param = %v, Result = %v, UserAgent = %v, CreateName = %v",
			//	logDb.StartTime,
			//	logDb.EndTime,
			//	logDb.SpendTime,
			//	logDb.Host,
			//	logDb.Url,
			//	logDb.Ipaddr,
			//	logDb.Method,
			//	logDb.Param,
			//	logDb.Result,
			//	logDb.UserAgent,
			//	logDb.CreateName)

			logger.WithFields(logrus.Fields{
				"startTime": logDb.StartTime,
				"endTime":   logDb.EndTime,
				"spendTime": logDb.SpendTime,
				"host":      logDb.Host,
				"url":       logDb.Url,
				"ipaddr":    logDb.Ipaddr,
				"method":    logDb.Method,
				"param":     logDb.Param,
				"result":    logDb.Result,
				"userAgent": logDb.UserAgent,
				"username":  logDb.CreateName,
			}).Info()
		}()
	}
}
